import Vue from 'vue'
import Vuex from 'vuex'

import axios from 'axios'
import { COUNTADD } from './types';

Vue.use(Vuex)    //全局注册声明使用vuex

export default new Vuex.Store({
  //一个对象就包含全部的应用层状态
  state: {
    count: 220,
    word: "2114 - 追进度",
    city: '武汉',
    msg: '困了吗',
    message: 'wh2114',
    data: {
      flag: true,
      test: "test - test -test"
    },
    num: 2114,
    list: []
  },
  mutations: {//传到mutation   修改state的数据
    [COUNTADD](state){
      state.count+=1;
    },
    countAdd(state) {
      state.count += 1
    },
    countDesc(state) {
      state.count -= 1
    },
    changeCount(state, payload) {    //payload   参数载荷
      state.count += payload
    },
    changeCityOnce(state, payload) {
      state.city = payload
    },
    changeWord(state, payload) {
      state.word = payload
    },
    changeMsg(state, payload) {
      state.msg = payload
    },
    changeDataFlag(state, payload) {
      // state.data.flag = !state.data.flag   对象的深浅拷贝
      state.data = {
        ...state.data,
        // flag:!state.data.flag
        flag: payload    // 最好用深拷贝
      }
    },
    changeDataTest(state, payload) {
      state.data = {
        ...state.data,
        test: payload
      }
    },
    changeNum(state, payload) {
      state.num += payload
    },
    increment(state) {
      state.num++
    },
    getNewWord(state, payload) {
      state.word = payload
    },
    getNewList(state,payload){
      state.list = payload;
    }
  },

  // action  可以包含任何异步操作
  // Action必须提交mutation
  // 同步操作可以省略Action  直接进入mutation
  actions: {
    increment(context) {
      context.commit('increment')
    },
    getNewWord({ commit }, payload) {
      commit('getNewWord', payload)
    },
    getNewTestAsync({ commit }) {
      axios.get("http://localhost:3000/test")
        .then(res => {
          console.log(res)
          commit('changeDataTest', res.data[0])
        })
    },
    async getNewList({commit}){
      let res = await axios.get("http://localhost:3000/list")
      commit('getNewList',res.data)
    }
  },
  modules: {
  },
  getters:{
    newCount(state){
      return state.count * 10 + 88
    }
  }
})
